package main

import "fmt"

// 求最大的不重复子串
func main() {
	s := "abcabcabcbb"
	length := lengthOfLongestSubstring(s)
	println(length)
}

// 优化减少一次for 循环的使用，充分利用 contians返回的index来构建子串
func lengthOfLongestSubstring(s string) int {
	substring := ""

	for i, v := range s {
		index := containsString(v, substring)
		if index == -1 {
			substring = s[:i]
		} else {
			substring = s[index+1 : len(substring)]
		}
		fmt.Println(substring)
	}
	return len(substring)
}

func containsString(v int32, str string) int {
	for i, value := range str {
		if int32(value) == v {
			return i
		}
	}
	return -1
}

// 使用了两边for循环一定是慢的
func lengthOfLongestSubstring2(s string) int {

	var arr []rune // 存储最小串
	max := 0
	for i := 0; i < len(s); i++ {
		arr = []rune{}
		arr = append(arr, rune(s[i]))

		for j := i + 1; j < len(s); j++ {
			if contains(rune(s[j]), arr) != -1 {
				break
			}
			arr = append(arr, rune(s[j]))
		}
		if max < len(arr) {
			max = len(arr)
		}
	}
	return max
}

func contains(j rune, arr []rune) int {
	for i, v := range arr {
		if v == j {
			return i
			break
		}
	}
	return -1
}
